package com.kkb.cglibproxy;

import com.kkb.aop.AOP;
import com.kkb.aop.TranAOP;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyFactory {
    private NBAService nbaService;

    private AOP aop;

    /*创建代理对象*/
    public Object getProxyInstance(NBAService nbaService,AOP aop){
        return Enhancer.create(nbaService.getClass(),
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        try {
                            aop.before();
                            Object invoke = methodProxy.invokeSuper(o, objects);
                            aop.after();
                            return invoke;
                        } catch (Throwable throwable) {
                            aop.exception();
                            throwable.printStackTrace();
                            throw throwable;
                        } finally {
                            aop.myFinally();
                        }
                    }
                });
    }

    public static void main(String[] args) {
        NBAService nbaService = new NBAService();
        AOP tranAOP = new TranAOP();
        NBAService proxyInstance = (NBAService) new CglibProxyFactory().getProxyInstance(nbaService,tranAOP);
        int res = proxyInstance.add("勇士",1006);
        System.out.println(res);
    }
}
